package com.zzyl.nursing.service.impl;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.PageBean;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDto;
import com.zzyl.nursing.dto.TimeSlotCountDto;
import com.zzyl.nursing.mapper.MemberOrdersMapper;
import com.zzyl.nursing.service.MemberOrdersService;
import com.zzyl.serve.domain.NursingProject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MemberOrdersServiceImpl implements MemberOrdersService {
    @Autowired
    private MemberOrdersMapper memberOrdersMapper;


    @Override
    public PageBean<NursingProject> findAllPage(String name, Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        List<NursingProject> list = memberOrdersMapper.findAllPage();
        Page<NursingProject> p =(Page<NursingProject>) list;
        PageBean<NursingProject> pb = new PageBean<>((int) p.getTotal(),list);
        return  pb;
    }

    @Override
    public NursingProject selectById(Long id) {
        NursingProject nursingProject = memberOrdersMapper.selectById(id);
        return nursingProject;
    }

    @Override
    public int getTodayCancelledCount() {
        // 获取当前用户ID
        Long userId = UserThreadLocal.get();

        // 获取当天开始和结束时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        // 查询当天取消预约数量
        Integer count = memberOrdersMapper.countTodayCancelledReservations(userId, startTime, endTime);

        // 处理可能的null值，确保返回int类型
        return count != null ? count : 0;
    }

    @Override
    public List<TimeSlotCountDto> getCountByTime() {
// 构造查询时间范围（当天00:00:00到23:59:59）
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);


        // 查询数据库中已预约的时间段及预约次数
        List<TimeSlotCountDto> bookedCounts = memberOrdersMapper.selectBookedCountByTime(startTime, endTime);


        return bookedCounts;




//        return bookedCounts.stream()
//                .filter(dto -> {
//                    LocalTime slotTime = dto.getTime().toLocalTime();
//                    return !slotTime.isBefore(LocalTime.of(8, 0)) &&
//                            !slotTime.isAfter(LocalTime.of(18, 0));
//                })
//                .collect(Collectors.toList());
    }

    @Override
    public boolean insertReservation(ReservationDto dto) {

            // 获取当前用户ID
            Long userId = UserThreadLocal.get();

            Reservation reservation = new Reservation();
            reservation.setId(userId);
            reservation.setMobile(dto.getMobile());
            reservation.setName(dto.getName());
            reservation.setTime(dto.getTime());
            reservation.setType(dto.getType());
            reservation.setVisitor(dto.getVisitor());
            reservation.setStatus(0); // 默认状态，0表示待报道
            reservation.setCreateTime(LocalDateTime.now());
            reservation.setUpdateTime(LocalDateTime.now());

            // 保存到数据库
            int result = memberOrdersMapper.insertReservation(reservation);
            return result > 0;
    }

    @Override
    public PageBean<Reservation> findReservationPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        List<Reservation> reservations = memberOrdersMapper.findReservationPage(pageNum, pageSize, status);
        Page<Reservation> p =(Page<Reservation>) reservations;
        PageBean<Reservation> pb = new PageBean<>((int) p.getTotal(),reservations);
        return pb;
    }


//    @Override
//    public List<TimeSlotCountDto> getCountByTime(LocalDateTime time) {
//        // 查询每个时间段已预约次数
//        List<TimeSlotCountDto> bookedCounts = memberOrdersMapper.selectBookedCountByTime(startTime);
//
//        // 计算剩余预约次数
//        bookedCounts.forEach(dto -> {
//            int remainingCount = MAX_RESERVATION_PER_TIME_SLOT - dto.getCount();
//            dto.setCount(remainingCount);
//        });
//
//        return bookedCounts;
//    }
}
